04 / 05

What is escape analysis in Go?

Escape analysis is a compile-time optimization where the Go compiler decides whether a variable can live on the stack (fast, automatically freed) or must be heap-allocated (GC-managed) based on its lifetime.

The compiler performs escape analysis to minimize heap allocations, reducing GC pressure. A variable escapes to the heap when its lifetime exceeds the function frame or when its size is dynamically determined.

When variables escape to the heap
  1. 1

    Returned by pointer: the caller holds the reference, variable must outlive the function

  2. 2

    Stored in an interface: concrete type is hidden, compiler cannot track lifetime statically

  3. 3

    Captured by a goroutine closure: goroutine may outlive the creating function

  4. 4

    Size unknown at compile time: dynamic slices and maps

  5. 5

    Too large for the stack: objects exceeding the stack size limit

Inspecting escape analysis